<?php

namespace app\api\service\v1;

use app\api\model\user\MoneyLog as MoneyLogModel;
use app\api\model\Wxapp as WxappModel;
//use app\api\model\WxappPrepayId as WxappPrepayIdModel;

use app\common\enum\user\moneylog\Scene;
use app\common\exception\BaseException;
use app\common\library\wechat\WxPay;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\enum\order\PayType as PayTypeEnum;
use app\common\model\dealer\Capital;
use app\factory\PayFactory;

class Payment
{
    /**
     * 构建订单支付参数
     * @param $user
     * @param $order
     * @param $payType
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public static function orderPayment($user, $order, $payType)
    {
        if ($payType == PayTypeEnum::WECHAT) {
            return self::wechat(
                $user,
                $order['order_id'],
                $order['order_no'],
                $order['pay_price'],
                OrderTypeEnum::MASTER
            );
        }
        return [];
    }

    /**
     * 构建微信支付
     * @param \app\api\model\User $user
     * @param $orderId
     * @param $orderNo
     * @param $payPrice
     * @param int $orderType
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public static function wechat(
        $user,
        $orderId,
        $orderNo,
        $payPrice,
        $orderType = OrderTypeEnum::MASTER
    )
    {

        // 统一下单API
        $wxConfig = WxappModel::getWxappCache($user['wxapp_id']);
        $WxPay = PayFactory::instance($wxConfig);
//        $WxPay = new WxPay($wxConfig);
        $payment = $WxPay->unifiedorder($orderNo, $user['open_id'], $payPrice, $orderType);
        // // 记录prepay_id
        // $model = new WxappPrepayIdModel;
        // $model->add($payment['prepay_id'], $orderId, $user['user_id'], $orderType);
        return $payment;
    }
    /**
     *  密码支付
     * @param $user
     * @param $order
     * @param $password
     * @param $payWay
     * @return bool
     * @throws BaseException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function balance($user,$order,$password,$payWay)
    {
        // 统一下单API
        $rea=static::checkPass($user,$password);

        if($rea==true){
            //如果成功，将支付失败次数清空
            db('user')->where('user_id',$user['user_id'])->setField('payfailure',0);
            //return self::PayBalance($order,$payWay);
             return  true;
        }else{
            throw new BaseException(['msg' => '支付失败，密码错误']);
        }
    }


    /**
     * 验证支付密码
     * @param $user
     * @param $password
     * @return bool
     * @throws BaseException
     */
    public static function checkPass($user,$password)
    {


        if(!trim($password)){
            throw new BaseException(['msg' => '请输入密码']);
        }
        // 当前用户信息
        if(!$user['pay_password']){
            throw new BaseException(['msg' => '请先设置支付密码']);
        }
        if($user['payfailure']==3){
            throw new BaseException(['msg' => '密码输入错误多次，请修改密码后再试']);
        }
        if($user['pay_password']!=yoshop_hash($password)){
            //如果失败，将支付失败次数加一
            db('user')->where('user_id',$user['user_id'])->setInc('payfailure');
            throw new BaseException(['msg' => '支付密码错误']);
        }

        return true;
    }


    /**
     *  扣除用户余额
     * @param $order array 订单详情
     * @param $payWay int 支付类型 10.储值余额支付 20.收益余额
     * @return bool
     * @throws BaseException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private static  function PayBalance($order,$payWay){

        if($payWay==10){
            //减用户余额
            self::setUserMoney($order);
        }elseif($payWay==20){
            //减用户收益余额
            self::setUserDealer($order);
        }
        return true;

    }

    /**
     *  储值余额消费
     * @param $order
     * @return int|true
     * @throws BaseException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private static function setUserMoney($order){
        $userModel=new \app\common\model\User();
        $user=$userModel->find($order['user_id']);
        if($user['money']<$order['pay_price']){
            throw new BaseException(['msg' => '储值余额不足，请充值后再支付']);
        }
        $res=$userModel->where(['user_id'=>$order['user_id'],'wxapp_id'=>$order['wxapp_id']])->setDec('money',$order['pay_price']);
        MoneyLogModel::add([
            'scene'=>Scene::CONSUME,
            'user_id' => $order['user_id'],
            'money' => -$order['pay_price'],
            'order_no' =>$order['order_no'],
        ]);
        return $res;
    }

    /**
     *  *  用户消费支出
     * @param $order
     * @return int|true
     * @throws BaseException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private static function setUserDealer($order){
        $userModel=new \app\common\model\dealer\User();
        $user=$userModel->find($order['user_id']);
        if($user['money']<$order['pay_price']){
            throw new BaseException(['msg' => '收益余额不足，请使用微信支付']);
        }
        $res=$userModel->where(['user_id'=>$order['user_id'],'wxapp_id'=>$order['wxapp_id']])->setDec('money',$order['pay_price']);
        if($res==1){
            // 用户余额变动明细
            Capital::add([
                //  'wxapp_id' =>$order['wxapp_id'],
                'user_id'  =>$order['user_id'],
                'flow_type'=>70,
                'money'    =>$order['pay_price'],
                'describe' =>'消费支出'
            ]);
            return $res;
        }
    }

}